%% 测试程序
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 用于矩阵数据采集板的测试，主要功能：
% 1.读取串口调试助手sscom5.13保存的*.DAT数据文件;
% 2.根据数据包大小绘图每个通道数据，ADC可单独绘图
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
close all;
clear all;

%filename = 'ReceivedTofile-COM11-2023_12_28_11-53-59.DAT';
rows=1;          %数据包个数=1，每次读取1包；
cols=258;       %数据包大小=258字节
packet_len = rows*cols;

% 读取标定文件目录
[file,path,indx]  = uigetfile('*.DAT','选择DAT文件');
filename = fullfile(path,file);
fprintf('file:%s\n',filename);

fid = fopen(filename);
A= zeros(rows,cols);
B=[];
C=[];
D=[];
ID = [];

tic;
cnts= zeros(1,'uint32');

%读取全部数据；
while ~feof(fid)
    A = fread(fid,[rows,cols],'uint8','b');  %'ieee-be'
    if  (length(A)==cols)
        checksum_calc = sum(A(1:cols-2)) ;
        checksum_calc = bitand(checksum_calc, 65535);
        chesksum_recv = A(cols-1) + A(cols)*256;        %低字节在前
        if(checksum_calc == chesksum_recv)
%             fprintf('ok \n');
        else
            fprintf("checksum: calc = %d; ",checksum_calc);
            fprintf("recv = %d; ",chesksum_recv);
            fprintf('error\n');
        end
        B=[B;A];
        ID = [ID;A(5:6)];   %编号
        C=[C;A(41: 256)];   %FS1~FS6柔性传感器数据
        cnts=cnts+1;
        fprintf('cnts=%d\n',cnts);
    end
end
fclose(fid);
toc;

packet_id = ID(:,1)+ID(:,2)*256;
figure();
hold on;
subplot(2,1,1);
plot(packet_id);
title('packet id');
subplot(2,1,2);
plot(diff(packet_id),'r');
title('id 差值');


%little endian
for j = 1:1:108
    D(:,j)=C(:,2*j-1) + C(:,2*j)*256;
end

D=D./100;
for i=1:6
figure;
hold on;
plot(D(:,(i-1)*18+1:i*18));
strTitle=sprintf("FS%d",i);
title(strTitle);
strName=strjoin([filename, strTitle, '.jpg']);
saveas(gcf,strName);
end

